package com.tag;


import com.common.BeanContainer;
import com.entity.Menu;
import com.facade.menu.IMenuFacadeR;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;

public class NavigatorTag extends TagSupport {

    private final Logger logger = LoggerFactory.getLogger(NavigatorTag.class);

    private String url;

    @Override
    public int doStartTag() throws JspException {
        try {
            JspWriter writer = pageContext.getOut();
            String lv2Name = "";
            String lv1Name = "";

            if (StringUtils.isBlank(url)) {
                return super.doStartTag();
            }

            IMenuFacadeR menuFacadeR = (IMenuFacadeR) BeanContainer.getBean("menuFacadeR");
            Menu menuLv2 = menuFacadeR.findUniqueByPropertyEqualTo("uri", url);
            if (null != menuLv2) {
                lv2Name = menuLv2.getName();
                Menu menuLv1 = menuFacadeR.findByPrimaryKey(menuLv2.getPid());
                if (null != menuLv1) {
                    lv1Name = menuLv1.getName();
                }
            }

            writer.write(createHtml(lv1Name, lv2Name));

        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        return super.doStartTag();
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    private String createHtml(String lv1Name, String lv2Name) {
        if (StringUtils.isBlank(lv1Name) || StringUtils.isBlank(lv2Name)) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        sb.append("<div class=\"pageheader\">");
        sb.append("    <h2>" + lv2Name + "</h2>");
        sb.append("    <div class=\"breadcrumb-wrapper\">");
        sb.append("        <span class=\"left color-999 font13\">您当前的位置：</span>");
        sb.append("        <ol class=\"breadcrumb left\">");
        sb.append("            <li>" + lv1Name + "</li>");
        sb.append("            <li>" + lv2Name + "</li>");
        sb.append("        </ol>");
        sb.append("    </div>");
        sb.append("</div>");
        return sb.toString();
    }

}